<?php

/**
 * Транслятор объектов в XSL-шаблоны
 */
class XSLTranslator implements iXSLTranslator {

	private
		$xmlTranslator  = null,
		$processor      = null,
		$maybeAdmin     = '';
		
	public function __construct () {
		$this->xmlTranslator = new XMLTranslator;
		
		$this->processor = new XSLTProcessor;
		$this->processor->registerPHPFunctions ();
		
		$this->maybeAdmin = CMSController::getInstance()->isAdminMode () ? 'admin/' : '';
	}
	
	/**
	 * Запускает обработку сайта на основе ответа модуля
	 * @param ModuleResponse $oResponse
	 * @param string $sTemplateFileName относительный путь до файла XSL-таблицы (главнй XSL-шаблон)
	 * @return string
	 */
	public function render (ModuleResponse $oResponse) {
		header ('Content-type: text/html; charset=utf-8');
		
		$templateFilename = ENGINE_ROOT . '/templates/' . $this->maybeAdmin . 'xsl/' . $oResponse->getTemplate() . '.xsl';
		
		if (!file_exists ($templateFilename)) {
			throw new CoreException (lang('error_template_not_found',__CLASS__) . $templateFilename);			
		}
		
		$xslTpl = new DOMDocument;
		$xslTpl->substituteEntities = true;
		$xslTpl->resolveExternals = true;
		$xslTpl->load ($templateFilename);
	
		$this->processor->importStyleSheet ($xslTpl);
		
		$xml = $this->xmlTranslator->buildPageResponse ($oResponse);
		
		$html = $this->processor->transformToXML ($xml);
		
		return $html;
	}

}